package op

import (
	"fmt"
	"github.com/rs/zerolog/log"
	"net/http"
	"webGoDemo/constant"
	"webGoDemo/model"
	"webGoDemo/utils"
)

type LogicOpService struct {
}

func (l *LogicOpService) Notify(notify model.NotifyRequestFromUI) (*model.CommonResult, error) {

	//从前端获取数据，进行解析，封装到
	requestToOP := parseUIRequestToOP(notify)
	//这里远程调用op的接口
	result, err := callOpNotify(requestToOP)
	if err != nil {
		log.Info().Msg("op返回notify 出错")
		return model.ReturnFail(err), nil
	}
	//将返回的结果封装到comm中
	comm := model.ReturnSuccess(result)
	return comm, nil
}

func (l *LogicOpService) CheckClusterState(instanceId, tenantId string) (int, error) {

	checkStateResponseFromOp := &model.OpGetInstanceStateResponse{}
	requestUrl := constant.BaseUrl + constant.CheckClusterStateUrl + "?instanceId=%s&tenantId=%s"
	url := fmt.Sprintf(requestUrl, instanceId, tenantId)
	log.Info().Str("requestUrl:", requestUrl).Send()
	err := utils.HttpDo(url, http.MethodGet, nil, checkStateResponseFromOp)
	if err != nil {
		return -1, err
	}
	if checkStateResponseFromOp.Code == 20000 {
		return checkStateResponseFromOp.Data, nil
	} else {
		return -1, err
	}

}

// 私有工具方法
func callOpNotify(notifyRequestToOP *model.NotifyRequestToOP) (*model.CommonResult, error) {

	responseFromOp := &model.CommonResult{}

	err := utils.HttpDo(constant.BaseUrl+constant.NotifyUrl, http.MethodPost, notifyRequestToOP, responseFromOp)
	if err != nil {
		return nil, err
	}
	return responseFromOp, nil
}

func parseUIRequestToOP(notify model.NotifyRequestFromUI) *model.NotifyRequestToOP {

	requestToOP := model.NotifyRequestToOP{
		InstanceId:   notify.InstanceId,
		TenantId:     notify.TenantId,
		InstanceInfo: constant.GetKafkaSpecific(notify.ResourceClass),
		HatchState:   true,
		RequestId:    "",
		ErrorMsg:     "",
	}
	return &requestToOP
}
